package com.me.study.rabbitmq.controller;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.MimeTypeUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author light
 * @version 1.0
 * @description: TODO
 * @date 2021/10/19 9:19
 */
@Configuration
public class MessageSender {
    @Bean
    public Demo demo() {
        return new Demo();
    }

    static class Demo implements CommandLineRunner {
        //springcloudstream中外部的消息生产者可以通过streamBridge来发送消息
        @Autowired
        StreamBridge streamBridge;

        @Override
        public void run(String... args) throws Exception {
            /*try {
                List<CorrelationData> results = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    String uuId = UUID.randomUUID().toString();
                    CorrelationData corr = new CorrelationData(uuId);
                    results.add(corr);
                    final Message<String> message = MessageBuilder.withPayload("testConfirm" + i)
                            .setHeader(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, corr)
                            .build();
                    //指定发送到的bindingName
                    streamBridge.send("FanoutExchange_OUTPUT", message);
                    System.out.println("发送:" + corr.getId());
                }
                for (CorrelationData correlationData : results) {
                    CorrelationData.Confirm confirm = correlationData.getFuture().get(10, TimeUnit.SECONDS);
                    if (confirm.isAck() == true) {
                        System.out.println("发送成功:" + correlationData.getId());
                    } else {
                        System.out.println("发送失败"+ correlationData.getId());
                        throw new Exception(confirm.getReason());
                    }
                }
            } catch (Exception e) {
                Thread.currentThread().interrupt();
                System.out.println();
            }*/
        }
    }
}
